"""
influxdb client RW keys
"""
from datetime import datetime

from influxdb_client import InfluxDBClient, Point, WritePrecision
from influxdb_client.client.write_api import SYNCHRONOUS

# You can generate a Token from the "Tokens Tab" in the UI
token = "0xKGRENxcMBrkBFe5_IZK4SuhibKkUOCtBYU_SzNV-_gqHw1dlrgBwzHa2m1hVTyv1hx0nS-_AgrzWAEwXZ3xw=="
org = "hitsz"
bucket = "climate"

client = InfluxDBClient(url="http://localhost:8086", token=token)

query = f'from(bucket: \\"{bucket}\\") |> range(start: -1h)'
query_api = client.query_api()

"""
Query: using Bind parameters
"""

p = {"_start": datetime.timedelta(hours=-1),
     "_location": "Prague",
     "_desc": True,
     "_floatParam": 25.1,
     "_every": datetime.timedelta(minutes=5)
     }

tables = query_api.query('''
    from(bucket:"my-bucket") |> range(start: _start)
        |> filter(fn: (r) => r["_measurement"] == "my_measurement")
        |> filter(fn: (r) => r["_field"] == "temperature")
        |> filter(fn: (r) => r["location"] == _location and r["_value"] > _floatParam)
        |> aggregateWindow(every: _every, fn: mean, createEmpty: true)
        |> sort(columns: ["_time"], desc: _desc)
''', params=p)

for table in tables:
    print(table)
    for record in table.records:
        print(str(record["_time"]) + " - " + record["location"] + ": " + str(record["_value"]))
